package com.theaf.basemodule.service.impl;

import com.theaf.basemodule.common.api.ParameterService;
import com.theaf.basemodule.common.condition.ParaCondition;
import com.theaf.basemodule.common.model.SysParameter;
import com.theaf.basemodule.common.vo.ParameterVO;
import com.theaf.basemodule.dao.SysParameterDAO;
import com.theaf.core.cache.CachesHelper;
import com.theaf.core.utils.SmExceptionHelper;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ParameterServiceImpl implements ParameterService {
    @Autowired
    private Mapper mapper;
    @Resource
    private SysParameterDAO sysParameterDAO;

    public static final String CACHE_NAME = "SMYW_PARAMETER_";


    @Override
    public Page<ParameterVO> findByCondition(ParaCondition condition) {
        Page<SysParameter> sysParameters = sysParameterDAO.findCustom(condition);
        return sysParameters.map(new Converter<SysParameter, ParameterVO>(){
            @Override
            public ParameterVO convert(SysParameter sysUser) {
                return mapper.map(sysUser,ParameterVO.class);
            }
        });
    }

    @Override
    public ParameterVO findByCode(String code) {
        SysParameter sysParameter = sysParameterDAO.findOne(code);
        if(sysParameter==null){
            throw SmExceptionHelper.sysCheckException(code+"参数找不到");
        }
        return mapper.map(sysParameter,ParameterVO.class);
    }

    @Override
    public void save(ParameterVO parameterVO) {
        CachesHelper.clearByPrefix(CACHE_NAME+parameterVO.getCode());
        sysParameterDAO.save(mapper.map(parameterVO,SysParameter.class));
    }

    @Override
    public void delete(String code) {
        SysParameter sysParameter = sysParameterDAO.findOne(code);
        if(sysParameter==null){
            throw SmExceptionHelper.sysCheckException(code+"参数找不到");
        }
        CachesHelper.clearByPrefix(CACHE_NAME+sysParameter.getCode());
        sysParameterDAO.delete(sysParameter);
    }
}
